package com.gss.plugin.oauth2.handler;

import com.alibaba.fastjson.JSONObject;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DYang
 * @date 2023/8/19
 * 自定义登录失败异常
 */
public class CustomAuthFailHandler implements AuthenticationFailureHandler {

    private String url;

    public CustomAuthFailHandler() {
    }

    public CustomAuthFailHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        R<Object> res = R.error(ConstantEnum.NON_AUTH);
        writer.write(JSONObject.toJSONString(res));
        writer.flush();
        writer.close();
    }
}
